package com.ethank.utils;


// import com.cnbai.pdf.HeaderMarkerEventHandler;
// import com.cnbai.pdf.PageEventHandler;
// import com.cnbai.pdf.WaterMarkEventHandler;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.core.io.ClassPathResource;

import com.ethank.config.pdf.PageEventHandler;
import com.itextpdf.html2pdf.ConverterProperties;
import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.io.font.PdfEncodings;
import com.itextpdf.io.source.ByteArrayOutputStream;
import com.itextpdf.kernel.events.PdfDocumentEvent;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.font.FontProvider;
/**
 * @author tf
 * @date 2024-09-06
 * @Description
 */

public class HtmlToPdfUtils {

    /**
     * 自定义水印
     */
    private static final String WATERMARK_TEXT = "青岛尚美数智酒店集团";

    /**
     * 页眉显示
     */
    private static final String headerText = "";

    /**
     * 页眉logo
     */
    private static final String logoUrl = "http://localhost/logo.jpg";

    /**
     * 自定义字体路径，ttc后缀的字体需要添加 -> ,0
     */
    private static final String FONT_PATH = "/font/simsun.ttc";

    /**
     * html 转 pdf
     *
     * @param inputStream  输入流
     * @param outputStream 输出流
     */
    public static void convertToPdf(InputStream inputStream, OutputStream outputStream) throws IOException {
        PdfWriter pdfWriter = new PdfWriter(outputStream);
        PdfDocument pdfDocument = new PdfDocument(pdfWriter);
        // 设置为 A4 大小和页边距
        // float margin = 10f; // 单位为毫米
        PageSize pageSize  = PageSize.TABLOID;
        // pageSize.setWidth(pageSize.getWidth()- margin * 2 );
        // pageSize.setHeight(pageSize.getHeight()- margin * 2 );
        // pageSize.setX(margin);
        // pageSize.setY(margin);

        // 设置页面大小
        pdfDocument.setDefaultPageSize(pageSize);
        // 添加中文字体支持
        ConverterProperties properties = new ConverterProperties();
        FontProvider fontProvider = new FontProvider();
        // 添加自定义字体, 例如宋体

        String os = System.getProperties().getProperty("os.name");
        String fontPath="";
        if (os.startsWith("win") || os.startsWith("Win")) {
            ClassPathResource classPathResource = new ClassPathResource(FONT_PATH);
            fontPath = classPathResource.getPath() + ",0";
        } else {
            fontPath = "/usr/share/fonts/myfonts/simsun.ttc,0";

        }
        PdfFont microsoft = PdfFontFactory.createFont(fontPath, PdfEncodings.IDENTITY_H, false);
        fontProvider.addFont(microsoft.getFontProgram(), PdfEncodings.IDENTITY_H);

        // 添加页眉
        // pdfDocument.addEventHandler(PdfDocumentEvent.START_PAGE, new HeaderMarkerEventHandler(microsoft, headerText, ""));

        // 添加水印
        // pdfDocument.addEventHandler(PdfDocumentEvent.INSERT_PAGE, new WaterMarkEventHandler(WATERMARK_TEXT));

        // 添加页码
        pdfDocument.addEventHandler(PdfDocumentEvent.END_PAGE, new PageEventHandler(microsoft));

        properties.setFontProvider(fontProvider);

        // 读取 Html 文件流，查找出当中的 &nbsp; 或出现类似的符号空格字符
        inputStream = readInputStream(inputStream);
        if (inputStream != null) {
            // 生成 pdf 文档
            HtmlConverter.convertToPdf(inputStream, pdfDocument, properties);
            pdfWriter.close();
            pdfDocument.close();
        } else {
            System.out.println("转换失败！");
        }
    }


    /**
     * 读取 HTML 流文件，并查询当中的 &nbsp; 或类似符号，并将其替换为空格
     */
    private static InputStream readInputStream(InputStream inputStream) {
        try {
            // 1. 创建字节数组输出流，用来输出读取到的内容
            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            // 2. 创建缓存大小，1KB
            byte[] buffer = new byte[1024];
            int len; // 每次读取到内容的长度

            // 3. 开始读取输入流中的内容
            while ((len = inputStream.read(buffer)) != -1) {
                baos.write(buffer, 0, len);
            }

            // 4. 把字节数组转换为字符串
            String content = baos.toString();

            // 5. 关闭输入流和输出流
            inputStream.close();
            baos.close();

            // 6. 判断 HTML 内容是否具有 HTML 的特殊字符标记
            Pattern compile = Pattern.compile("&[a-zA-Z]{1,10};", Pattern.CASE_INSENSITIVE);
            Matcher matcher = compile.matcher(content);
            String replaceAll = matcher.replaceAll("");

            // 7. 将字符串转化为输入流返回
            return getStringStream(replaceAll);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 将一个字符串转化为输入流
     */
    private static InputStream getStringStream(String sInputString) {
        if (sInputString != null && !sInputString.trim().isEmpty()) {
            try {
                return new ByteArrayInputStream(sInputString.getBytes());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
